{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Pandas sort_values() - 按值排序详解\n",
    "\n",
    "本教程详细介绍如何使用 `sort_values()` 方法对 DataFrame 和 Series 按值进行排序。\n",
    "\n",
    "## 目录\n",
    "1. sort_values() 基础用法\n",
    "2. 单列排序\n",
    "3. 多列排序\n",
    "4. 排序参数详解\n",
    "5. 处理缺失值\n",
    "6. 自定义排序\n",
    "7. 性能优化技巧"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 导入库"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "import warnings\n",
    "warnings.filterwarnings('ignore')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1. sort_values() 基础用法\n",
    "\n",
    "### 方法说明\n",
    "\n",
    "`sort_values()` 是 Pandas 中最常用的排序方法，可以按照一列或多列的值进行排序。\n",
    "\n",
    "**语法:**\n",
    "```python\n",
    "df.sort_values(by, axis=0, ascending=True, inplace=False, \n",
    "               kind='quicksort', na_position='last', \n",
    "               ignore_index=False, key=None)\n",
    "```\n",
    "\n",
    "**主要参数:**\n",
    "- `by`: 排序的列名或列名列表\n",
    "- `ascending`: True(升序) 或 False(降序)，默认 True\n",
    "- `axis`: 0(按行排序) 或 1(按列排序)，默认 0\n",
    "- `inplace`: 是否直接修改原 DataFrame，默认 False\n",
    "- `na_position`: 缺失值位置，'first' 或 'last'，默认 'last'\n",
    "\n",
    "**特点:**\n",
    "- ✅ 支持单列和多列排序\n",
    "- ✅ 可以指定升序或降序\n",
    "- ✅ 默认返回新 DataFrame\n",
    "- ✅ 处理缺失值的灵活选项\n",
    "\n",
    "**适用场景:** 需要按数据值排序时"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 示例1: 创建示例数据"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "原始数据:\n",
      "   姓名  数学  英语  语文 班级\n",
      "0  张三  85  90  88  A\n",
      "1  李四  92  85  90  B\n",
      "2  王五  78  95  85  A\n",
      "3  赵六  96  82  94  B\n",
      "4  孙七  88  91  87  A\n"
     ]
    }
   ],
   "source": [
    "# 创建学生成绩数据\n",
    "df = pd.DataFrame({\n",
    "    '姓名': ['张三', '李四', '王五', '赵六', '孙七'],\n",
    "    '数学': [85, 92, 78, 96, 88],\n",
    "    '英语': [90, 85, 95, 82, 91],\n",
    "    '语文': [88, 90, 85, 94, 87],\n",
    "    '班级': ['A', 'B', 'A', 'B', 'A']\n",
    "})\n",
    "\n",
    "print(\"原始数据:\")\n",
    "print(df)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 示例2: 最简单的排序\n",
    "\n",
    "按数学成绩升序排序。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "按数学成绩升序排序:\n",
      "   姓名  数学  英语  语文 班级\n",
      "2  王五  78  95  85  A\n",
      "0  张三  85  90  88  A\n",
      "4  孙七  88  91  87  A\n",
      "1  李四  92  85  90  B\n",
      "3  赵六  96  82  94  B\n"
     ]
    }
   ],
   "source": [
    "df_sorted = df.sort_values('数学')\n",
    "print(\"按数学成绩升序排序:\")\n",
    "print(df_sorted)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 示例3: 降序排序\n",
    "\n",
    "按数学成绩降序排序。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "按数学成绩降序排序:\n",
      "   姓名  数学  英语  语文 班级\n",
      "3  赵六  96  82  94  B\n",
      "1  李四  92  85  90  B\n",
      "4  孙七  88  91  87  A\n",
      "0  张三  85  90  88  A\n",
      "2  王五  78  95  85  A\n"
     ]
    }
   ],
   "source": [
    "df_sorted = df.sort_values('数学', ascending=False)\n",
    "print(\"按数学成绩降序排序:\")\n",
    "print(df_sorted)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2. 单列排序\n",
    "\n",
    "详细介绍单列排序的各种用法。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 示例1: 按不同数据类型排序\n",
    "\n",
    "演示数值、字符串等不同类型的排序。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 按字符串排序\n",
    "df_sorted = df.sort_values('姓名')\n",
    "print(\"按姓名排序:\")\n",
    "print(df_sorted)\n",
    "\n",
    "# 按班级排序\n",
    "df_sorted = df.sort_values('班级')\n",
    "print(\"\\n按班级排序:\")\n",
    "print(df_sorted)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 示例2: Series 排序\n",
    "\n",
    "对 Series 进行排序。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 提取数学成绩 Series\n",
    "math_scores = df['数学']\n",
    "print(\"原始数学成绩:\")\n",
    "print(math_scores)\n",
    "\n",
    "# 排序\n",
    "sorted_scores = math_scores.sort_values()\n",
    "print(\"\\n排序后:\")\n",
    "print(sorted_scores)\n",
    "\n",
    "# 降序排序\n",
    "sorted_scores_desc = math_scores.sort_values(ascending=False)\n",
    "print(\"\\n降序排序:\")\n",
    "print(sorted_scores_desc)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 示例3: 保留原索引 vs 重置索引\n",
    "\n",
    "控制排序后的索引行为。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 保留原索引（默认）\n",
    "df_sorted = df.sort_values('数学')\n",
    "print(\"保留原索引:\")\n",
    "print(df_sorted)\n",
    "\n",
    "# 重置索引\n",
    "df_sorted = df.sort_values('数学', ignore_index=True)\n",
    "print(\"\\n重置索引:\")\n",
    "print(df_sorted)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 3. 多列排序\n",
    "\n",
    "使用多个列进行排序，处理复杂的排序需求。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 方法说明\n",
    "\n",
    "多列排序时，先按第一列排序，如果第一列有相同值，再按第二列排序，以此类推。\n",
    "\n",
    "**语法:**\n",
    "```python\n",
    "df.sort_values(['列1', '列2', ...], ascending=[True, False, ...])\n",
    "```\n",
    "\n",
    "**特点:**\n",
    "- 按列表顺序依次排序\n",
    "- 可以为每列指定不同的排序方向\n",
    "- 优先级从左到右递减\n",
    "\n",
    "**适用场景:** 需要多级排序时"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 示例1: 双列排序\n",
    "\n",
    "先按班级排序，再按数学成绩排序。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df_sorted = df.sort_values(['班级', '数学'])\n",
    "print(\"先按班级，再按数学成绩排序:\")\n",
    "print(df_sorted)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 示例2: 不同排序方向\n",
    "\n",
    "班级升序，数学成绩降序。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df_sorted = df.sort_values(['班级', '数学'], ascending=[True, False])\n",
    "print(\"班级升序，数学成绩降序:\")\n",
    "print(df_sorted)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 示例3: 三列排序\n",
    "\n",
    "班级、数学、英语三级排序。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df_sorted = df.sort_values(['班级', '数学', '英语'], \n",
    "                          ascending=[True, False, False])\n",
    "print(\"三级排序（班级升序，数学和英语降序）:\")\n",
    "print(df_sorted)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 示例4: 复杂排序场景\n",
    "\n",
    "创建更复杂的数据进行演示。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 创建包含重复值的数据\n",
    "df_complex = pd.DataFrame({\n",
    "    '部门': ['销售', '技术', '销售', '技术', '销售', '技术'],\n",
    "    '级别': ['初级', '高级', '中级', '初级', '高级', '中级'],\n",
    "    '工资': [5000, 12000, 8000, 7000, 10000, 9000],\n",
    "    '年龄': [25, 35, 30, 28, 32, 29]\n",
    "})\n",
    "\n",
    "print(\"复杂数据:\")\n",
    "print(df_complex)\n",
    "\n",
    "# 多级排序：部门 -> 级别 -> 工资\n",
    "df_sorted = df_complex.sort_values(['部门', '级别', '工资'], \n",
    "                                  ascending=[True, True, False])\n",
    "print(\"\\n多级排序结果:\")\n",
    "print(df_sorted)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 4. 排序参数详解\n",
    "\n",
    "详细说明 sort_values() 的各个参数。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 参数1: axis 参数\n",
    "\n",
    "控制排序的方向（行或列）。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 创建示例数据\n",
    "df_demo = pd.DataFrame({\n",
    "    'A': [3, 1, 4],\n",
    "    'B': [2, 5, 1],\n",
    "    'C': [6, 3, 2]\n",
    "})\n",
    "\n",
    "print(\"原始数据:\")\n",
    "print(df_demo)\n",
    "\n",
    "# axis=0: 按行排序（默认）\n",
    "df_sorted = df_demo.sort_values('A', axis=0)\n",
    "print(\"\\naxis=0 按行排序（按A列的值排序行）:\")\n",
    "print(df_sorted)\n",
    "\n",
    "# axis=1: 按列排序\n",
    "df_sorted = df_demo.sort_values(0, axis=1)  # 按第0行的值排序列\n",
    "print(\"\\naxis=1 按列排序（按第0行的值排序列）:\")\n",
    "print(df_sorted)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 参数2: kind 参数\n",
    "\n",
    "指定排序算法。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 不同的排序算法\n",
    "algorithms = ['quicksort', 'mergesort', 'heapsort']\n",
    "\n",
    "df_test = pd.DataFrame({\n",
    "    '数值': [3, 1, 4, 1, 5, 9, 2, 6]\n",
    "})\n",
    "\n",
    "print(\"原始数据:\")\n",
    "print(df_test['数值'].tolist())\n",
    "\n",
    "for alg in algorithms:\n",
    "    sorted_data = df_test.sort_values('数值', kind=alg)\n",
    "    print(f\"\\n{alg} 排序结果:\")\n",
    "    print(sorted_data['数值'].tolist())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 参数3: inplace 参数\n",
    "\n",
    "控制是否直接修改原 DataFrame。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df_original = pd.DataFrame({\n",
    "    '数值': [3, 1, 4, 2]\n",
    "})\n",
    "\n",
    "print(\"原始数据:\")\n",
    "print(df_original)\n",
    "\n",
    "# inplace=False（默认）\n",
    "df_new = df_original.sort_values('数值')\n",
    "print(\"\\ninplace=False，原数据:\")\n",
    "print(df_original)\n",
    "print(\"\\n新数据:\")\n",
    "print(df_new)\n",
    "\n",
    "# inplace=True\n",
    "df_original.sort_values('数值', inplace=True)\n",
    "print(\"\\ninplace=True，原数据被修改:\")\n",
    "print(df_original)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 5. 处理缺失值\n",
    "\n",
    "排序时如何处理 NaN 值。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 方法说明\n",
    "\n",
    "`na_position` 参数控制缺失值在排序结果中的位置。\n",
    "\n",
    "**选项:**\n",
    "- `'last'`: 缺失值放在最后（默认）\n",
    "- `'first'`: 缺失值放在最前\n",
    "\n",
    "**特点:**\n",
    "- 缺失值不参与大小比较\n",
    "- 位置可以自定义\n",
    "- 对升序和降序都有效\n",
    "\n",
    "**适用场景:** 数据中包含缺失值时"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 示例1: 创建包含缺失值的数据"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df_na = pd.DataFrame({\n",
    "    '姓名': ['张三', '李四', '王五', '赵六'],\n",
    "    '分数': [85, np.nan, 92, 78]\n",
    "})\n",
    "\n",
    "print(\"包含缺失值的数据:\")\n",
    "print(df_na)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 示例2: 缺失值在最后（默认）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df_sorted = df_na.sort_values('分数')\n",
    "print(\"缺失值在最后（默认）:\")\n",
    "print(df_sorted)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 示例3: 缺失值在最前"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df_sorted = df_na.sort_values('分数', na_position='first')\n",
    "print(\"缺失值在最前:\")\n",
    "print(df_sorted)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 示例4: 降序排序中的缺失值"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 降序排序，缺失值在最后\n",
    "df_sorted = df_na.sort_values('分数', ascending=False)\n",
    "print(\"降序排序，缺失值在最后:\")\n",
    "print(df_sorted)\n",
    "\n",
    "# 降序排序，缺失值在最前\n",
    "df_sorted = df_na.sort_values('分数', ascending=False, na_position='first')\n",
    "print(\"\\n降序排序，缺失值在最前:\")\n",
    "print(df_sorted)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 6. 自定义排序\n",
    "\n",
    "使用 key 参数进行自定义排序。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 方法说明\n",
    "\n",
    "`key` 参数允许在排序前对数据进行转换。\n",
    "\n",
    "**语法:**\n",
    "```python\n",
    "df.sort_values('列名', key=lambda x: 转换函数(x))\n",
    "```\n",
    "\n",
    "**特点:**\n",
    "- 可以应用任意转换函数\n",
    "- 不改变原始数据\n",
    "- 支持复杂的排序逻辑\n",
    "\n",
    "**适用场景:** 需要特殊排序逻辑时"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 示例1: 按字符串长度排序"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df_names = pd.DataFrame({\n",
    "    '姓名': ['张三', '李四五', '王', '赵六七八'],\n",
    "    '年龄': [25, 30, 35, 28]\n",
    "})\n",
    "\n",
    "print(\"原始数据:\")\n",
    "print(df_names)\n",
    "\n",
    "# 按姓名长度排序\n",
    "df_sorted = df_names.sort_values('姓名', key=lambda x: x.str.len())\n",
    "print(\"\\n按姓名长度排序:\")\n",
    "print(df_sorted)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 示例2: 按绝对值排序"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df_numbers = pd.DataFrame({\n",
    "    '数值': [-5, 3, -8, 1, -2, 7]\n",
    "})\n",
    "\n",
    "print(\"原始数据:\")\n",
    "print(df_numbers)\n",
    "\n",
    "# 按绝对值排序\n",
    "df_sorted = df_numbers.sort_values('数值', key=lambda x: abs(x))\n",
    "print(\"\\n按绝对值排序:\")\n",
    "print(df_sorted)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 示例3: 自定义排序顺序"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df_grades = pd.DataFrame({\n",
    "    '学生': ['张三', '李四', '王五', '赵六'],\n",
    "    '等级': ['B', 'A', 'C', 'A']\n",
    "})\n",
    "\n",
    "print(\"原始数据:\")\n",
    "print(df_grades)\n",
    "\n",
    "# 自定义等级顺序：A > B > C\n",
    "grade_order = {'A': 1, 'B': 2, 'C': 3}\n",
    "df_sorted = df_grades.sort_values('等级', key=lambda x: x.map(grade_order))\n",
    "print(\"\\n按自定义等级顺序排序:\")\n",
    "print(df_sorted)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 示例4: 复杂的自定义排序"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df_complex = pd.DataFrame({\n",
    "    '产品': ['iPhone13', 'iPhone12', 'iPhone14', 'iPhone11'],\n",
    "    '价格': [6999, 5999, 7999, 4999]\n",
    "})\n",
    "\n",
    "print(\"原始数据:\")\n",
    "print(df_complex)\n",
    "\n",
    "# 按产品名中的数字排序\n",
    "import re\n",
    "def extract_number(x):\n",
    "    return x.str.extract(r'(\\d+)').astype(int)\n",
    "\n",
    "df_sorted = df_complex.sort_values('产品', key=extract_number)\n",
    "print(\"\\n按产品名中的数字排序:\")\n",
    "print(df_sorted)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 7. 性能优化技巧\n",
    "\n",
    "提高排序性能的方法和建议。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 技巧1: 选择合适的排序算法"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import time\n",
    "\n",
    "# 创建大型数据集\n",
    "large_df = pd.DataFrame({\n",
    "    '数值': np.random.randint(1, 1000, 10000)\n",
    "})\n",
    "\n",
    "algorithms = ['quicksort', 'mergesort', 'heapsort']\n",
    "times = {}\n",
    "\n",
    "for alg in algorithms:\n",
    "    start_time = time.time()\n",
    "    large_df.sort_values('数值', kind=alg)\n",
    "    end_time = time.time()\n",
    "    times[alg] = end_time - start_time\n",
    "\n",
    "print(\"不同算法的性能对比（10000行数据）:\")\n",
    "for alg, t in times.items():\n",
    "    print(f\"{alg}: {t:.4f} 秒\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 技巧2: 避免不必要的复制"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 如果不需要保留原数据，使用 inplace=True\n",
    "df_test = pd.DataFrame({\n",
    "    '数值': np.random.randint(1, 100, 1000)\n",
    "})\n",
    "\n",
    "# 方式1：创建副本（占用更多内存）\n",
    "start_time = time.time()\n",
    "df_sorted = df_test.sort_values('数值')\n",
    "time_copy = time.time() - start_time\n",
    "\n",
    "# 方式2：就地排序（节省内存）\n",
    "df_test_copy = df_test.copy()\n",
    "start_time = time.time()\n",
    "df_test_copy.sort_values('数值', inplace=True)\n",
    "time_inplace = time.time() - start_time\n",
    "\n",
    "print(f\"创建副本: {time_copy:.6f} 秒\")\n",
    "print(f\"就地排序: {time_inplace:.6f} 秒\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 技巧3: 预处理数据类型"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 字符串数字转换为数值类型排序更快\n",
    "df_str = pd.DataFrame({\n",
    "    '数值': ['100', '20', '300', '5', '150']\n",
    "})\n",
    "\n",
    "print(\"字符串排序:\")\n",
    "print(df_str.sort_values('数值'))\n",
    "\n",
    "# 转换为数值类型\n",
    "df_str['数值'] = df_str['数值'].astype(int)\n",
    "print(\"\\n数值排序:\")\n",
    "print(df_str.sort_values('数值'))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 总结\n",
    "\n",
    "### sort_values() 参数总结\n",
    "\n",
    "| 参数 | 默认值 | 说明 | 常用值 |\n",
    "|------|--------|------|--------|\n",
    "| `by` | 必需 | 排序的列名 | 字符串或列表 |\n",
    "| `ascending` | True | 排序方向 | True(升序), False(降序) |\n",
    "| `axis` | 0 | 排序轴 | 0(行), 1(列) |\n",
    "| `inplace` | False | 是否修改原数据 | True, False |\n",
    "| `kind` | 'quicksort' | 排序算法 | 'quicksort', 'mergesort', 'heapsort' |\n",
    "| `na_position` | 'last' | 缺失值位置 | 'first', 'last' |\n",
    "| `ignore_index` | False | 是否重置索引 | True, False |\n",
    "| `key` | None | 自定义排序函数 | lambda 函数 |\n",
    "\n",
    "### 关键要点\n",
    "\n",
    "1. **单列排序**: `df.sort_values('列名')`\n",
    "2. **多列排序**: `df.sort_values(['列1', '列2'])`\n",
    "3. **降序排序**: `ascending=False`\n",
    "4. **处理缺失值**: `na_position='first'` 或 `'last'`\n",
    "5. **自定义排序**: 使用 `key` 参数\n",
    "6. **性能优化**: 选择合适的算法，考虑 `inplace=True`\n",
    "7. **数据类型**: 确保数据类型适合排序\n",
    "\n",
    "### 最佳实践\n",
    "\n",
    "```python\n",
    "# ✅ 推荐\n",
    "df.sort_values('列名')  # 简单排序\n",
    "df.sort_values(['列1', '列2'], ascending=[True, False])  # 多列排序\n",
    "df.sort_values('列名', key=lambda x: x.str.len())  # 自定义排序\n",
    "\n",
    "# ❌ 避免\n",
    "df.sort_values('列名', inplace=True)  # 除非确定不需要原数据\n",
    "```"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "ml311",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
